<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { updateUserAvatarService } from '@/api/user'

const user = useUserStore()
const updateRef = ref('')
const imageUrl = ref(user.userInfo.user_pic)

const onSelectFlie = (uploadFile) => {
  //基于 FlieReader 读取图片做预览
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imageUrl.value = reader.result
  }
}

const onUpdateAvatar = async () => {
 await updateUserAvatarService(imageUrl.value)
 await user.getUserInfo()
  ElMessage.success('更新成功')
}
</script>

<template>
  <PageContainer title="更新头像">
     <el-upload
        ref="updateRef"
        class="avatar-uploader"
        :auto-upload="false"
        :on-change="onSelectFlie"
        :show-file-list="false"
     >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
       <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <br>
       <el-button @click="updateRef.$el.querySelector('input').click()" type="primary" size="large" :icon="Plus">提交</el-button>
       <el-button @click="onUpdateAvatar" type="success" size="large" :icon="Upload">点击上传</el-button>
  </PageContainer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
